package com.example.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 幻
 * @date 2021-05-18 16:12
 */
@Service
public class TokenUtils {

    //token过期时间
    private static long EXPIRE_TIME;

    @Value("${token.expireTime}")
    private void setExpireTime(long expireTime) {
        EXPIRE_TIME = expireTime;
    }

    //JWT密钥
    private static String SECRET;

    @Value("${token.secret}")
    private void setSecret(String secret) {
        TokenUtils.SECRET = secret;
    }

    //redisToken过期时间
    public static long REDIS_EXPIRE_TIME;

    @Value("${token.redisExpireTime}")
    private void setRedisExpireTime(long redisExpireTime) {
        REDIS_EXPIRE_TIME = redisExpireTime;
    }

    /**
     * 创建token
     */
    public static String createToken(String username, Long current) {
        //token过期时间
        Date date = new Date(current + EXPIRE_TIME * 1000);

        //jwt的header部分
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        //使用jwt的api生成token
        String token = null;//签名
        try {
            token = JWT.create()
                    .withHeader(map)
                    //私有声明
                    .withClaim("username", username)
                    //当前时间截点
                    .withClaim("current", current)
                    //过期时间
                    .withExpiresAt(date)
                    //签发时间
                    .withIssuedAt(new Date())
                    .sign(Algorithm.HMAC256(SECRET));
        } catch (IllegalArgumentException | JWTCreationException e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 获取username
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    //获取过期时间
    public static Long getExpire(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("current").asLong();
        } catch (Exception e) {
            return null;
        }
    }

    //校验token的有效性，1、token的header和payload是否没改过；2、没有过期
    public static boolean verify(String token) {
        try {
            //解密
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
